package com.xingkeduo.service.cms.marketing.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.xingkeduo.dao.TActivityCodeMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCouponBagMapper;
import com.xingkeduo.feign.ManageUserFeignService;
import com.xingkeduo.model.example.TActivityCodeExample;
import com.xingkeduo.model.example.TActivityCodeExample.Criteria;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCouponBagExample;
import com.xingkeduo.model.param.ActivityCodeParam;
import com.xingkeduo.model.param.ActivityCodeParam.ActivityCodeStatusEnum;
import com.xingkeduo.model.po.TActivityCode;
import com.xingkeduo.model.po.TMarketingReceiveHistory;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCouponBag;
import com.xingkeduo.model.vo.ActivityCodeResponseVo;
import com.xingkeduo.service.cms.marketing.ActivityCodeService;
import com.xingkeduo.service.cms.marketing.MarketingReceiveService;
import com.xingkeduo.service.consume.UserService;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.StringUtils;
import com.xingkeduo.util.tool.ResponseMessage;

@Service
public class ActivityCodeServiceImpl implements ActivityCodeService {

	@Autowired
	TActivityCodeMapper tActivityCodeMapper;
	@Autowired
	ManageUserFeignService manageUserFeignService;
	@Autowired
	TMarketingReceiveHistoryCouponBagMapper tMarketingReceiveHistoryCouponBagMapper;
	@Autowired
	@Qualifier(value = "marketingCouponBagReceiveService")
	MarketingReceiveService marketingCouponBagReceiveService;
	@Autowired
	UserService userService;

	@Override
	public ResponseMessage queryRedeemCodeList(ActivityCodeParam redeemCodeExample) {
		TActivityCodeExample example = new TActivityCodeExample();
		Criteria criteria = example.createCriteria();
		if (StringUtils.isNotBlank(redeemCodeExample.getCode())) {
			criteria.andCodeEqualTo(redeemCodeExample.getCode());
		}
		if (redeemCodeExample.getStatus() != null) {
			criteria.andStatusEqualTo(redeemCodeExample.getStatus());
		}
		if (redeemCodeExample.getType() != null) {
			criteria.andTypeEqualTo(redeemCodeExample.getType());
		}
		// 券Id,券名称
		if (StringUtils.isNumeric(redeemCodeExample.getMarketingInfo())) {
			criteria.andMarketingIdEqualTo(Long.valueOf(redeemCodeExample.getMarketingInfo()));
		} else if (StringUtils.isNotBlank(redeemCodeExample.getMarketingInfo())) {
			criteria.andMarketingNameLike("%" + redeemCodeExample.getMarketingInfo()+ "%");
		}
		// 用户id，昵称，手机号
		if (StringUtils.isNotBlank(redeemCodeExample.getUserInfo())) {
			List<Long> userIdList = userService.queryUserIdsByMobileOrId(redeemCodeExample.getUserInfo());
			criteria.andUserIdIn(userIdList);
		}
		if (StringUtils.isNotBlank(redeemCodeExample.getCreateStartTime())) {
			System.out.println(redeemCodeExample.getCreateStartTime());
			criteria.andCreateTimeGreaterThanOrEqualTo(DateUtils.parseDate(redeemCodeExample.getCreateStartTime()));
		}
		if (StringUtils.isNotBlank(redeemCodeExample.getCreateEndTime())) {
			redeemCodeExample.setCreateEndTime(redeemCodeExample.getCreateEndTime() + " 24:00:00");
			criteria.andCreateTimeLessThan(DateUtils.parseDate(redeemCodeExample.getCreateEndTime()));
		}
		example.setOrderByClause(" id desc");
		PageHelper.startPage(redeemCodeExample.getPageNum(), redeemCodeExample.getPageSize());
		List<TActivityCode> list = tActivityCodeMapper.selectByExample(example);
		PageInfo<TActivityCode> page = new PageInfo<>(list);
		PageInfo<ActivityCodeResponseVo> pageReturn = new PageInfo<>();
		BeanUtils.copyProperties(page, pageReturn);
		List<ActivityCodeResponseVo> returnList = Lists.transform(list,
				new Function<TActivityCode, ActivityCodeResponseVo>() {
					@Override
					public ActivityCodeResponseVo apply(TActivityCode history) {
						ActivityCodeResponseVo responseVo = new ActivityCodeResponseVo();
						BeanUtils.copyProperties(history, responseVo);
						if(history.getUserId() !=null) {
							Map<String,String> returnMap = userService.queryOnlyUserInfosByUserId(history.getUserId());
							if(MapUtils.isNotEmpty(returnMap)) {
								responseVo.setUserInfo(history.getUserId()+"_"+returnMap.get("name"));
								responseVo.setUserMobile(returnMap.get("phone"));
							}	
						}
						return responseVo;
					}
				});
		pageReturn.setList(returnList);
		return ResponseMessage.ok(pageReturn);
	}

	@Override
	public ResponseMessage auditRedeemCode(Long redeemCodeId, Integer status) {
		TActivityCode tActivityCode = new TActivityCode();
		tActivityCode.setId(redeemCodeId);
		tActivityCode.setStatus(status);
		int count = tActivityCodeMapper.updateByPrimaryKeySelective(tActivityCode);
		if (count <= 0) {
			return ResponseMessage.error("更新兑换码状态失败", 500);
		}
		return ResponseMessage.ok("更新兑换码状态成功");

	}

	@Override
	public ResponseMessage getRedeemCodeDetail(Long redeemCodeReceiveHistoryId) {
		// 领取信息
		TActivityCode tActivityCode = tActivityCodeMapper.selectByPrimaryKey(redeemCodeReceiveHistoryId);
		if(tActivityCode.getStatus().intValue() != ActivityCodeStatusEnum.USED.getCode() 
				|| tActivityCode.getMarketingId() == null 
				|| StringUtils.isBlank(tActivityCode.getCode())) {
			return ResponseMessage.error("参数不全，无法匹配领取信息",500); 
		}
		TMarketingReceiveHistoryCouponBagExample historyExample = new TMarketingReceiveHistoryCouponBagExample();
		com.xingkeduo.model.example.TMarketingReceiveHistoryCouponBagExample.Criteria criteria = historyExample.createCriteria();
		criteria.andMarketingBagIdEqualTo(tActivityCode.getMarketingId())
		        .andRedeemCodeEqualTo(tActivityCode.getCode());
		if(tActivityCode.getUserId()!=null) {
			criteria.andUserIdEqualTo(tActivityCode.getUserId());
		}
		List<TMarketingReceiveHistoryCouponBag> historyList = tMarketingReceiveHistoryCouponBagMapper
				.selectByExample(historyExample);
		if (CollectionUtils.isEmpty(historyList)) {
			return ResponseMessage.error("参数不全，无法匹配领取信息",500);
		}
		TMarketingReceiveHistory history = historyList.get(0);
		return marketingCouponBagReceiveService.getUserMarketingUseDetail(history.getId(), history.getMarketingType());
	}

	@Override
	public ResponseMessage getRedeemCodeUseHisory(Long redeemCodeReceiveHistoryId) {
		// 领取信息
		TActivityCode tActivityCode = tActivityCodeMapper.selectByPrimaryKey(redeemCodeReceiveHistoryId);
		TMarketingReceiveHistoryCouponBagExample historyExample = new TMarketingReceiveHistoryCouponBagExample();
		historyExample.createCriteria().andUserIdEqualTo(tActivityCode.getUserId())
				.andMarketingBagIdEqualTo(tActivityCode.getMarketingId()).andRedeemCodeEqualTo(tActivityCode.getCode());
		List<TMarketingReceiveHistoryCouponBag> historyList = tMarketingReceiveHistoryCouponBagMapper
				.selectByExample(historyExample);
		if (CollectionUtils.isEmpty(historyList)) {
			return ResponseMessage.error("无用户领取信息",500);
		}
		TMarketingReceiveHistory history = historyList.get(0);
		return marketingCouponBagReceiveService.getMarketingBagUseHisory(history.getId(), history.getMarketingType());
	}

}
